/* Copyright - Apache License 2.0
 * 
 * The project "kyou" is
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kyou.pack;

import java.util.ArrayList;

import net.kyou.data.dquery.DQuery;
import net.kyou.pack.segment.Segment;
import net.kyou.util.KyouXmlUtils;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 报文组包样式单元 <br/>
 * 组包样式单元描述了对于某一类元素的组包方式
 * 
 * @author NuclearG (<a href="mailto:nuclearg@163.com">nuclearg@163.com</a>)
 */
public class StyleItem {
    /**
     * 该组包样式单元隶属于的组包样式定义
     */
    public final StyleSpecification spec;

    /**
     * 该组包样式单元适用于的元素
     */
    final DQuery target;
    /**
     * 段列表
     */
    final Segment[] segments;

    /**
     * 从XML中初始化一个StyleItem实例
     * 
     * @param e
     *            XML节点
     * @param spec
     *            该组包样式单元隶属于的组包样式定义
     */
    StyleItem(Element e, StyleSpecification spec) {
        this.spec = spec;
        
        /**
         * <pre>
         *      <style target="...">
         *              <text>&lt;</text>
         *              <s>n</s>
         *              <text>&gt;</text>
         *              <s>m</s>
         *              <text>&lt;/</text>
         *              <s>n</s>
         *              <text>&gt;</text>
         *      </style>
         * </pre>
         */

        // 初始化target
        String target = KyouXmlUtils.selectText(e, "@target");
        this.target = new DQuery(target);

        // 初始化segments
        NodeList nodes = e.getChildNodes();
        ArrayList<Segment> segments = new ArrayList<Segment>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node instanceof Element)
                segments.add(Segment.__new((Element) node, this.spec.config.encoding, this));
            else {
                String text = node.getTextContent().trim();
                if (text.length() != 0)
                    segments.add(Segment.__text(text, this.spec.config.encoding, this));
            }
        }

        this.segments = segments.toArray(new Segment[0]);
    }
}
